package com.zhang.dft_project.handler;

import com.zhang.dft_project.common.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常控制
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({BindException.class})
    public R doBindException(BindException bindException){
        BindingResult bindingResult = bindException.getBindingResult();
        R r = new R();
        //是否存在异常
        if (bindingResult.hasErrors()){
            StringBuilder sb = new StringBuilder();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                sb.append(fieldError.getField()).append("提示：").append(fieldError.getDefaultMessage());
                sb.append("-----------");
            }

            r.setCode(601);
            r.setMsg("请求参数错误，错误信息：" + sb.toString());
        }
        return r;
    }

    @ExceptionHandler({Exception.class})
    public R doOtherException(Exception e){
        R r = new R();
        r.setCode(602);
        r.setMsg("" + e.getMessage());
        return r;
    }
}
